package tezhongbing.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class SocketClient {
	public static void main(String[] args) throws UnknownHostException, IOException {
		Scanner scanner = null;
		Socket socket = null;
		try {
			scanner = new Scanner(System.in);
			socket = new Socket("localhost", 8888);
			System.out.println("已经连接上服务器，现在可以输入消息进行通信了！");
			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			
			String sendMsg = scanner.nextLine();
			writer.write(sendMsg);
			writer.newLine();
			writer.flush();
			String receiveMsg = null;
			while(!"close".equalsIgnoreCase(receiveMsg=reader.readLine())){
				System.out.println("服务器返回："+receiveMsg);
				sendMsg = scanner.nextLine();
				writer.write(sendMsg);
				writer.newLine();
				writer.flush();
			}
			System.out.println("我是客户端，结束了！");
		}finally{
			if(scanner != null){
				scanner.close();
			}
			if(socket != null){
				socket.close();
			}
		}
	}
}
